Replace existing cell with new cell in DGN
The below code snippet shows how to replace existing cell element with the new cell element. It replaces all the references of cell from sheet and drawings models also.
//Required References
using System;
using System.Diagnostics;
using Bentley.Interop.MicroStationDGN;
using Bentley.GeometryNET;
using BMI = Bentley.MstnPlatformNET.InteropServices;
public void ReplaceCell()
{
//Get all graphical elements cache from DGN file
Bentley.Interop.MicroStationDGN.ElementCache elementCache = Bentley.MstnPlatformNET.InteropServices.Utilities.ComApp.ActiveModelReference.GraphicalElementCache;
//Scan to get all elements from DGN and get first cell element for replace
ElementEnumerator elementEnumerator = elementCache.Scan();
try
{
Bentley.Interop.MicroStationDGN.CellElement cellElement = null;
while (elementEnumerator.MoveNext())
{
//Get the first cell element
Bentley.Interop.MicroStationDGN.Element currentElement = elementEnumerator.Current;
if (currentElement.IsCellElement())
{
cellElement = (Bentley.Interop.MicroStationDGN.CellElement)currentElement;
break;
}
}
if (cellElement == null) return;
//create origin point for cell placement
Bentley.Interop.MicroStationDGN.Point3d origin = new Bentley.Interop.MicroStationDGN.Point3d
{
X = cellElement.Origin.X,
Y = cellElement.Origin.Y,
Z = cellElement.Origin.Z
};
//create scale point
double scale = 2.0;
Bentley.Interop.MicroStationDGN.Point3d pScale = new Bentley.Interop.MicroStationDGN.Point3d
{
X = scale,
Y = scale,
Z = scale
};
//create rotation matrix
Angle angle = Angle.FromDegrees(0.0);
Bentley.Interop.MicroStationDGN.Matrix3d mRotation = BMI.Utilities.ComApp.Matrix3dFromAxisAndRotationAngle(2, angle.Radians);
//string updatedCellName = "Arrow - PvtMrk - Rt U Turn";
string updatedCellName = "Cab_Class 150";
//Create new cell element
Bentley.Interop.MicroStationDGN.CellElement updatedCellElement = BMI.Utilities.ComApp.CreateCellElement2(updatedCellName, ref origin, ref pScale, true, ref mRotation);
if (updatedCellElement != null)
{
//Update the first cell element from the list of cells with new cell element, this will replace sheet and drawing references also
BMI.Utilities.ComApp.ActiveModelReference.ReplaceElement(cellElement, updatedCellElement);
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}